package com.ylkj.patient.ui.activities.webview;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.examination.mlib.constants.ARouterConstants;
import com.examination.mlib.constants.KitArouterConstants;
import com.examination.mlib.interfaceapi.MineBackApi;
import com.example.minemodule.Utils.MineUtils;
import com.google.gson.Gson;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ActivityManagerUtils;
import com.ylkj.patient.ui.activities.webview.bean.WebJavaScriptBean_A;
import com.ylkj.patient.ui.activities.webview.bean.WebJavaScriptBean_B;
import com.ylkj.patient.utils.AppReactUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class WebJavascriptInterface {

    private Context context;


    public WebJavascriptInterface(Context context) {
        this.context = context;
    }

    /**
     * 图片长按
     *
     * @param src 图片的链接
     */
    @JavascriptInterface
    public void imageLongClick(String src) {
        Toast.makeText(context, "图片长按", Toast.LENGTH_SHORT).show();
    }

    /**
     * 图片长按
     */
    @JavascriptInterface
    public void imageLongClick() {
        Toast.makeText(context, "图片长按", Toast.LENGTH_SHORT).show();
    }

    /**
     * 图片点击
     *
     * @param src 图片的链接
     */
    @JavascriptInterface
    public void imageClick(String src) {
        Toast.makeText(context, "图片点击", Toast.LENGTH_SHORT).show();
    }

    /**
     * 图片保存
     *
     * @param src 图片的链接
     */
    private File outputImage;
    private String imagePath;

    @JavascriptInterface
    public void saveImage(String src) {
//        Bitmap bitmap = null;
//        if (src.startsWith("http")) {
//            bitmap = BitmapUtils.GetImageInputStream(src);
//        } else {
//            bitmap = BitmapUtils.base64ToBitmap(src.substring(src.indexOf(",") + 1));
//        }
//        if (bitmap == null) {
//            ALog.Log_i(this.getClass().getName(), "bitmap is null");
//        } else {
////            BitmapUtils.saveBitmap(bitmap, imagePath);
//            BitmapUtils.saveImageToGallery(context,bitmap);
//            Toast.makeText(ActivityUtils.getTopActivity(), "图片保存成功", Toast.LENGTH_SHORT).show();
//        }

    }


    /**
     * 打开页面
     */
    @JavascriptInterface
    public void openRnPage(String pluginId, String compontName) {
//        ALog.i();
        ALog.i(WebJavascriptInterface.class.getSimpleName(), " openRnPage has‘t params : ");
        AppReactUtils.INSTANCE.push(context, pluginId, compontName);
    }

    /**
     * 打开页面
     */
    @JavascriptInterface
    public void openRnPage(String pluginId, String compontName, String paramsJson) {
        ALog.i(paramsJson);
//        Log.e("shouldOverr","openPage: " + pluginId + " " + compontName + " " + paramsJson);

        if (TextUtils.isEmpty(paramsJson)) {
            openRnPage(pluginId, compontName);
            return;
        }
        ALog.i(WebJavascriptInterface.class.getSimpleName(), "openRnPage has params : ");
        Bundle bundle = new Bundle();
        Map<String, Object> extMap = (Map<String, Object>) JSON.parse(paramsJson);
        Set<Map.Entry<String, Object>> entries = extMap.entrySet();
        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> next = iterator.next();
            bundle.putString(next.getKey(), next.getValue().toString());
        }
        if (compontName.equals("DrugDetail") || compontName.equals("Search")) {
            AppReactUtils.INSTANCE.push(context, KitArouterConstants.CART_DOCTORBUNDLE, compontName, bundle);
        } else {
            AppReactUtils.INSTANCE.push(context, pluginId, compontName, bundle);
        }
    }

    /**
     * 打开就诊人
     */
    @JavascriptInterface
    public void openInquiryPage() {
        ALog.i(WebJavascriptInterface.class.getSimpleName());
        AppReactUtils.INSTANCE.push(context, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.SeeDoctorDetails);
    }

    /**
     * 点击药品跳转详情
     *
     * @param pluginId      模块名
     * @param componentName 页面名
     * @param params        参数jsonString
     */
    @JavascriptInterface
    public void imageLongClick(String pluginId, String componentName, String params) {
        Bundle bundle = new Bundle();
        try {
            JSONObject jsonObject = new JSONObject(params);
            if (jsonObject.has("doctorId")) {
                bundle.putString("doctorId", jsonObject.getLong("doctorId") + "");
            }
            if (jsonObject.has("packetId")) {
                bundle.putLong("packetId", jsonObject.getLong("packetId"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MineBackApi mineBackApi = (MineBackApi) ARouter.getInstance().build(ARouterConstants.MineModuleImpl).navigation();
        mineBackApi.Android2RnPush(context, pluginId, componentName, bundle);
    }

    /**
     * @param tag
     * @param params
     * @param promise
     */
    private final String A = "openHealthBaseData"; //打开血脂记录页面
    private final String B = "openRecordBlood"; //打开记录血脂页面
    private final String C = "openCustomer"; // 打开客服页面

    @JavascriptInterface
    public void toNativeGeneralAction(String tag, String json) {
        ALog.e(tag);
        ALog.e(json);
        Gson gson = new Gson();
        switch (tag) {
            case A:
                WebJavaScriptBean_A webJavaScriptBean_A = gson.fromJson(json, WebJavaScriptBean_A.class);
                Bundle bundle = new Bundle();
                bundle.putInt("inquiringPatientId", Integer.parseInt(webJavaScriptBean_A.getInquiringPatientId()));
                bundle.putBoolean("bloodPage", webJavaScriptBean_A.isBloodPage());
                bundle.putInt("level", Integer.parseInt(webJavaScriptBean_A.getLevel()));
                bundle.putString("booldValue", webJavaScriptBean_A.getBloodValue());
                bundle.putString("booldDesctibe", String.valueOf(webJavaScriptBean_A.getBooldDesctibe()));
                bundle.putString("updateTime", webJavaScriptBean_A.getUpdateTime());
                bundle.putString("bloodFatReferenceBasis", webJavaScriptBean_A.getBloodFatReferenceBasis());
                bundle.putString("healthAdvice", "");
                ArrayList<String> strings = new ArrayList<>();
                if (webJavaScriptBean_A.getBloodFatHealthAdviceList() != null) {
                    for (String s : webJavaScriptBean_A.getBloodFatHealthAdviceList()) {
                        strings.add(s);
                    }
                }
                bundle.putStringArrayList("healthAdviceList", strings);
                ArrayList<String> strings1 = new ArrayList<>();
                if (webJavaScriptBean_A.getBloodFatReferenceRange() != null) {
                    for (String s : webJavaScriptBean_A.getBloodFatReferenceRange()) {
                        strings1.add(s);
                    }
                }
                bundle.putStringArrayList("bloodFatReferenceRange", strings1);
                MineUtils.push(context, KitArouterConstants.MY_BUNDLE, "HealthBaseData", bundle);
                break;
            case B:
                WebJavaScriptBean_B webJavaScriptBean_B = gson.fromJson(json, WebJavaScriptBean_B.class);
                ARouter.getInstance().build(ARouterConstants.RecordWeightActivity)
                        .withInt("inquiringPatientId", Integer.valueOf(webJavaScriptBean_B.getInquiringPatientId()).intValue())
                        .withInt("pageType", webJavaScriptBean_B.getType())
                        .withInt("bloodFatRecordSource", webJavaScriptBean_B.getBloodSource())
                        .navigation();
                break;
            case C: {
                JSONObject jsonObject = null;
                String moorType = "";
                String moorId = "";
                if (TextUtils.isEmpty(json)) {
                    try {
                        jsonObject = new JSONObject(json);
                        if (jsonObject.has("moorType")) {
                            moorType = jsonObject.getString("moorType");
                        }
                        if (TextUtils.isEmpty(moorType)) {
                            moorType = "common";
                        } else {
                            switch (moorType) {
                                case "common": {
                                    break;
                                }
                                case "doctor": {
                                    if (jsonObject.has("doctorId")) {
                                        moorId = jsonObject.getString("doctorId");
                                    }
                                    break;
                                }
                                case "drug": {
                                    if (jsonObject.has("drugId")) {
                                        moorId = jsonObject.getString("drugId");
                                    }
                                    break;
                                }
                                case "packet": {
                                    if (jsonObject.has("packetId")) {
                                        moorId = jsonObject.getString("packetId");
                                    }
                                    break;
                                }
                                case "order": {
                                    if (jsonObject.has("orderId")) {
                                        moorId = jsonObject.getString("orderId");
                                    }
                                    break;
                                }
                                case "chargeOrder": {
                                    if (jsonObject.has("orderId")) {
                                        moorId = jsonObject.getString("orderId");
                                    }
                                    break;
                                }
                            }
                        }
                    } catch (JSONException e) {
                        //数据解析异常Log
                        ALog.e("WebJavascripterface", e.getMessage());
                        e.printStackTrace();
                    }
                }

                if (!TextUtils.isEmpty(moorId)) {
                    ARouter.getInstance().build(ARouterConstants.ContractWebviewActivity)
                            .withString("title", "在线客服")
                            .withBoolean("isShowLoading", true)
                            .withString("moorType", moorType)
                            .withString("moorId", moorId)
                            .navigation();
                } else {
                    ARouter.getInstance().build(ARouterConstants.ContractWebviewActivity)
                            .withString("title", "在线客服")
                            .withBoolean("isShowLoading", true)
                            .withString("moorType", moorType)
                            .navigation();
                }
            }
            break;
            default:
                ALog.e("tag不存在");
                break;
        }
    }


    @JavascriptInterface
    public void toNativeBackHomeAction(String params1, String params2, String params3) {
        ALog.e("toNativeBackAction");
        ARouter.getInstance().build(ARouterConstants.MAIN_ACTIVITY).navigation();
    }

    @JavascriptInterface
    public void toNativeBackAction(String params1, String params2, String params3) {
        ALog.e("toNativeBackAction");
        ActivityManagerUtils.getLastestActivity().finish();
    }

}
